//
//  MakerTools.m
//  MedicalMaterial
//
//  Created by 刘甲奇 on 2017/1/14.
//  Copyright © 2017年 刘甲奇. All rights reserved.
//

#import "MakerTools.h"

@implementation MakerTools
+ (BOOL)isPhoneNumber:(NSString *)mobile
{
    NSString * phoneRegex = @"^1(3[0-9]|4[57]|5[0-35-9]|(7[0[059]|6｜7｜8])|8[0-9])\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

+(int)checkIsHaveNumAndLetter:(NSString*)password
{
    //数字条件
    NSRegularExpression *tNumRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    //符合数字条件的有几个字节
    NSUInteger tNumMatchCount = [tNumRegularExpression numberOfMatchesInString:password
                                                                       options:NSMatchingReportProgress
                                                                         range:NSMakeRange(0, password.length)];
    
    //英文字条件
    NSRegularExpression *tLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    //符合英文字条件的有几个字节
    NSUInteger tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString:password options:NSMatchingReportProgress range:NSMakeRange(0, password.length)];
    
    if (tNumMatchCount == password.length) {
        //全部符合数字，表示沒有英文
        return 1;
    } else if (tLetterMatchCount == password.length) {
        //全部符合英文，表示沒有数字
        return 2;
    } else if (tNumMatchCount + tLetterMatchCount == password.length) {
        //符合英文和符合数字条件的相加等于密码长度
        return 3;
    } else {
        return 4;
        //可能包含标点符号的情況，或是包含非英文的文字，这里再依照需求详细判断想呈现的错误
    }
}
+ (NSString *)getCurrentTimestamp
{
    
    NSDate* dat = [NSDate date];
    
    NSTimeInterval a=[dat timeIntervalSince1970];
    
    NSString*timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    
    return timeString;
}
+ (NSTimeInterval)getTimeFromString:(NSString *)time
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    
    // 3.利用时间格式化对象让字符串转换成时间 (自动转换0时区/东加西减)
    NSDate *date = [formatter dateFromString:time];
    return [date timeIntervalSince1970];
}

+ (NSString *)getWeekTimeStamp
{
    NSDate * date = [NSDate date];

    //一周的秒数
    NSTimeInterval time = 7 * 24 * 60 * 60;
    //下周就把"-"去掉
    NSDate *lastWeek = [date dateByAddingTimeInterval:-time];
    NSTimeInterval timeFloat = [lastWeek timeIntervalSince1970];
    
    return [NSString stringWithFormat:@"%0.f",timeFloat];
}
+ (NSString *)getDayZeroTimeWith:(NSInteger)day
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[[NSDate alloc] init]];
    
    [components setDay:([components day]-day )];
    NSDate *dayDate = [cal dateFromComponents:components];
    NSTimeInterval timeFloat = [dayDate timeIntervalSince1970];
    
    return [NSString stringWithFormat:@"%0.f",timeFloat];
}
+ (NSArray *)getWeekDay
{
    NSMutableArray *dayArray = [NSMutableArray array];
    
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[[NSDate alloc] init]];
    for (int i = 0; i < 7; i++) {
        
        if (i == 0) {
            [components setDay:([components day]-6)];
        }else{
            [components setDay:([components day]+1)];
        }
        NSDate *dayDate = [cal dateFromComponents:components];
        NSTimeInterval timeFloat = [dayDate timeIntervalSince1970];
        NSString *timeString = [NSString stringWithFormat:@"%f",timeFloat];
    
        [dayArray addObject:[self getDayFromInterval:timeString]];
    }
    
    return dayArray;
}
+ (NSString *)getDayFromInterval:(NSString *)timeIntervalString
{
   return [self getFormatTimeWithFormatter:@"MM-dd" intervalString:timeIntervalString];
}

+ (NSString *)getFormatTime:(NSString *)intervalString
{
    if (!intervalString ||[intervalString isEqualToString:@"0"])
    {
        return @"";
    }
    return [self getFormatTimeWithFormatter:@"yyyy-MM-dd HH:mm:ss" intervalString:intervalString];
    
}
+ (NSString *)getFormatTimeWithFormatter:(NSString *)formatter intervalString:(NSString *)intervalString
{
    NSTimeInterval timeSecond = [intervalString floatValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeSecond];
    
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formatter];
    return  [dateFormatter stringFromDate:date];
}

+ (void)CallPhone:(NSString *)phoneNumberString
{
    NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",phoneNumberString];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

+ (BOOL)saveToSandBox:(NSString *)fileName withSavedObject:(NSObject *)obj
{
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",documentPath,fileName];
    LELog(@"%s---%d---%@",__func__,__LINE__,filePath);
    return [NSKeyedArchiver archiveRootObject:obj toFile:filePath];
}

+ (id )readFromSandBox:(NSString *)fileName
{
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",documentPath,fileName];
    return [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
//清除用户的信息
+ (void)clearUserInfo
{
    //清除 document
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    [self clearCacheWithFilePath:documentPath];
    
    //preference 文件夹
    [self resetDefaults];

    //caches 文件夹
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    [self clearCacheWithFilePath:cachesPath];
}

/**
 清除偏好设置
 */
+(void)resetDefaults
{
    
    NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
    
    //获取一个快照字典
    NSDictionary* dict = [defs dictionaryRepresentation];
    
    for(id key in dict) {
        
        [defs removeObjectForKey:key];
        
    }
    
    [defs synchronize];
}


/**
 <#Description#>

 @param path <#path description#>
 @return <#return value description#>
 */
+ (NSString *)getCacheSizeWithFilePath:(NSString *)path
{
    // 获取“path”文件夹下的所有文件
    NSArray *subPathArr = [[NSFileManager defaultManager] subpathsAtPath:path];
    
    NSString *filePath  = nil;
    NSInteger totleSize = 0;
    
    for (NSString *subPath in subPathArr){
        
        // 1. 拼接每一个文件的全路径
        filePath =[path stringByAppendingPathComponent:subPath];
        // 2. 是否是文件夹，默认不是
        BOOL isDirectory = NO;
        // 3. 判断文件是否存在
        BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
        
        // 4. 以上判断目的是忽略不需要计算的文件
        if (!isExist || isDirectory || [filePath containsString:@".DS"]){
            // 过滤: 1. 文件夹不存在  2. 过滤文件夹  3. 隐藏文件
            continue;
        }
        
        // 5. 指定路径，获取这个路径的属性
        NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
        /**
         attributesOfItemAtPath: 文件夹路径
         该方法只能获取文件的属性, 无法获取文件夹属性, 所以也是需要遍历文件夹的每一个文件的原因
         */
        
        // 6. 获取每一个文件的大小
        NSInteger size = [dict[@"NSFileSize"] integerValue];
        
        // 7. 计算总大小
        totleSize += size;
    }
    
    //8. 将文件夹大小转换为 M/KB/B
    NSString *totleStr = nil;
    
    if (totleSize > 1000 * 1000){
        totleStr = [NSString stringWithFormat:@"%.1fM",totleSize / 1000.0f /1000.0f];
        
    }else if (totleSize > 1000){
        totleStr = [NSString stringWithFormat:@"%.1fKB",totleSize / 1000.0f ];
        
    }else{
        if (totleSize<100) {
            totleSize=0;
        }
        totleStr = [NSString stringWithFormat:@"%.1fB",totleSize / 1.0f];
    }
    
    return totleStr;
}

+ (BOOL)clearCacheWithFilePath:(NSString *)path{
    
    //拿到path路径的下一级目录的子文件夹
    NSArray *subPathArr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
    
    NSString *filePath = nil;
    
    NSError *error = nil;
    
    for (NSString *subPath in subPathArr)
    {
        filePath = [path stringByAppendingPathComponent:subPath];
        NSLog(@"filePath---%@",filePath);
        //删除子文件夹
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        if (error) {
            return NO;
        }
    }
    return YES;
}

/**
 降序的算法

 @param originalArray <#originalArray description#>
 @return <#return value description#>
 */
+ (NSMutableArray *)descend:(NSMutableArray *)originalArray
{
    [originalArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2)
     {
         
         if ([self getTimeFromString:obj1] < [self getTimeFromString:obj2])
         {
             return NSOrderedAscending;
             
         }
         else
         {
             return NSOrderedDescending;
         }
     }];
    return originalArray;
}
+ (NSString *)hexFromUIColor:(UIColor *)color
{
    if (CGColorGetNumberOfComponents(color.CGColor) < 4)
    {
        const CGFloat *components = CGColorGetComponents(color.CGColor);
        color = [UIColor colorWithRed:components[0]
                                green:components[0]
                                 blue:components[0]
                                alpha:components[1]];
    }
    
    if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {
        return [NSString stringWithFormat:@"#FFFFFF"];
    }
    
    return [NSString stringWithFormat:@"%d,%d,%d", (int)((CGColorGetComponents(color.CGColor))[0]*255.0),
            (int)((CGColorGetComponents(color.CGColor))[1]*255.0),
            (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];
}
+ (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType goodsUrl:(NSString *)url
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    NSString* thumbURL =  @"https://mobile.umeng.com/images/pic/home/social/img-1.png";
    
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"欢迎使用民生商家" descr:@"民生商家致力于更好服务社区老人！" thumImage:thumbURL];
    //设置网页地址
    shareObject.webpageUrl = url;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error)
        {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else
        {
            if ([data isKindOfClass:[UMSocialShareResponse class]])
            {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];

}
@end






